﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace VFTray
{
	internal class MemoryState
	{
		internal EventHandler EventRise;//上升沿
		internal EventHandler EventFall;//下降沿

		internal MemoryState()
		{
		}

		internal MemoryState(bool initValue)
		{
			_value = initValue;
		}

		internal bool Value => _value;
		internal bool HI => _value;
		internal bool LO => (!_value);
		internal bool EdgeRise => _riseEdge;
		internal bool EdgeFall => _fallEdge;

		private bool _value = false;
		private bool _riseEdge = false;
		private bool _fallEdge = false;

		private bool _coilRise = false;
		private bool _coilFall = false;

		public bool CoilRise
		{
			get
			{
				if (_value && _coilRise == false)
				{
					_coilRise = true;
					return true;
				}
				else
					return false;
			}
			set { _coilRise = value; }
		}

		public bool CoilFall
		{
			get
			{
				if (_value == false && _coilFall == false)
				{
					_coilFall = true;
					return true;
				}
				else
				{
					return false;
				}
			}
			set { _coilFall = value; }
		}



		private ThreadUtility.DelayHS time_Keep = new ThreadUtility.DelayHS();

		internal void Update(bool bv)
		{
			_riseEdge = (_value == false && bv == true);
			_fallEdge = (_value == true && bv == false);

			if (_value != bv) time_Keep.Clear();//status keep

			_value = bv;
			//if (bv == false)
			//{
			//	delay.Clear();
			//}
			if (EventRise != null && _riseEdge) EventRise(this, null);
			if (EventFall != null && _fallEdge) EventFall(this, null);
		}

		//public int DPOS = 0;
		//public void Update(bool bv, int dpos)
		//{
		//	_riseEdge = (_value == false && bv == true);
		//	if (_riseEdge) DPOS = dpos;

		//	_fallEdge = (_value == true && bv == false);
		//	_value = bv;

		//	//if (bv == false)
		//	//{
		//	//	delay.Clear();
		//	//}

		//	if (EventRise != null && _riseEdge) EventRise(this, null);
		//	if (EventFall != null && _fallEdge) EventFall(this, null);
		//}

		internal int GetHoldMs()
		{
			return (int)time_Keep.GetTimeMs();
			//if (_value)
			//	return (int)time_Keep.GetTimeMs();
			//else
			//	return 0;
		}

	}
}
